{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Source of the materials**: Biopython Tutorial and Cookbook (adapted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Sequence Objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Biological sequences are arguably the central object in Bioinformatics, and in this chapter we'll introduce the Biopython mechanism for dealing with sequences, Seq object.\n",
    "Later we will introduce the related SeqRecord object, which combines the sequence information with any annotation.\n",
    "\n",
    "Sequences are essentially strings of letters like AGTACACTGGT, which seems very natural since this is the most common way that sequences are seen in biological file formats.\n",
    "\n",
    "There are two important differences between Seq objects and standard Python strings.\n",
    "First of all, they have different methods.  Although the Seq object supports many of the same methods as a plain string, its translate() method differs by doing biological translation, and there are also additional biologically relevant methods like reverse_complement().\n",
    "Secondly, the Seq object has an important attribute, alphabet, which is an object describing what the individual characters making up the sequence string ``mean'', and how they should be interpreted.  For example, is AGTACACTGGT a DNA sequence, or just a protein sequence that happens to be rich in Alanines, Glycines, Cysteines\n",
    "and Threonines?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from Bio.Seq import Seq\n",
    "from Bio.Alphabet import IUPAC\n",
    "from Bio.Data import CodonTable\n",
    "from Bio.SeqUtils import GC"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sequences and Alphabets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The alphabet object is perhaps the important thing that makes the Seq object more than just a string. The currently available alphabets for Biopython are defined in the Bio.Alphabet module. We'll use the IUPAC alphabets (http://www.chem.qmw.ac.uk/iupac/) here to deal with some of our favorite objects: DNA, RNA and Proteins.\n",
    "\n",
    "Bio.Alphabet.IUPAC provides basic definitions for proteins, DNA and RNA, but additionally provides the ability to extend and customize the basic definitions. For instance, for proteins, there is a basic IUPACProtein class, but there is an additional ExtendedIUPACProtein class providing for the additional elements ``U'' (or ``Sec'' for selenocysteine) and ``O'' (or ``Pyl'' for pyrrolysine), plus the ambiguous symbols ``B'' (or ``Asx'' for asparagine or aspartic acid), ``Z'' (or ``Glx'' for glutamine or glutamic acid), ``J'' (or ``Xle'' for leucine isoleucine) and ``X'' (or ``Xxx'' for an unknown amino acid). For DNA you've got choices of IUPACUnambiguousDNA, which provides for just the basic letters, IUPACAmbiguousDNA (which provides for ambiguity letters for every possible situation) and ExtendedIUPACDNA, which allows letters for modified bases. Similarly, RNA can be represented by IUPACAmbiguousRNA or IUPACUnambiguousRNA.\n",
    "\n",
    "The advantages of having an alphabet class are two fold. First, this gives an idea of the type of information the Seq object contains. Secondly, this provides a means of constraining the information, as a means of type checking.\n",
    "\n",
    "Now that we know what we are dealing with, let's look at how to utilize this class to do interesting work.\n",
    "You can create an ambiguous sequence with the default generic alphabet like this:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('AGTACACTGGT', Alphabet())"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq = Seq(\"AGTACACTGGT\")\n",
    "my_seq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Alphabet()"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq.alphabet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, where possible you should specify the alphabet explicitly when creating your sequence objects - in this case an unambiguous DNA alphabet object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('AGTACACTGGT', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from Bio.Alphabet import IUPAC\n",
    "my_seq = Seq(\"AGTACACTGGT\", IUPAC.unambiguous_dna)\n",
    "my_seq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "IUPACUnambiguousDNA()"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq.alphabet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Unless of course, this really is an amino acid sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('AGTACACTGGT', IUPACProtein())"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_prot = Seq(\"AGTACACTGGT\", IUPAC.protein)\n",
    "my_prot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "IUPACProtein()"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_prot.alphabet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sequences act like strings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In many ways, we can deal with Seq objects as if they were normal Python strings, for example getting the length, or iterating over the elements:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 G\n",
      "1 A\n",
      "2 T\n",
      "3 C\n",
      "4 G\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "my_seq = Seq(\"GATCG\", IUPAC.unambiguous_dna)\n",
    "for index, letter in enumerate(my_seq):\n",
    "    print(\"%i %s\" % (index, letter))\n",
    "print(len(my_seq))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can access elements of the sequence in the same way as for strings (but remember, Python counts from zero!):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "G\n",
      "T\n",
      "G\n"
     ]
    }
   ],
   "source": [
    "print(my_seq[0]) #first letter\n",
    "print(my_seq[2]) #third letter\n",
    "print(my_seq[-1]) #last letter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Seq object has a .count() method, just like a string.\n",
    "Note that this means that like a Python string, this gives a\n",
    "non-overlapping count:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "print(\"AAAA\".count(\"AA\"))\n",
    "print(Seq(\"AAAA\").count(\"AA\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For some biological uses, you may actually want an overlapping count\n",
    "(i.e. $3$ in this trivial example). When searching for single letters, this\n",
    "makes no difference:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "32\n",
      "9\n",
      "46.875\n"
     ]
    }
   ],
   "source": [
    "my_seq = Seq('GATCGATGGGCCTATATAGGATCGAAAATCGC', IUPAC.unambiguous_dna)\n",
    "print(len(my_seq))\n",
    "print(my_seq.count(\"G\"))\n",
    "print(100 * float(my_seq.count(\"G\") + my_seq.count(\"C\")) / len(my_seq))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While you could use the above snippet of code to calculate a GC\\%, note that  the __Bio.SeqUtils__ module has several GC functions already built.  For example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "46.875"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq = Seq('GATCGATGGGCCTATATAGGATCGAAAATCGC', IUPAC.unambiguous_dna)\n",
    "GC(my_seq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that using the __Bio.SeqUtils.GC()__ function should automatically cope with mixed case sequences and the ambiguous nucleotide S which means G or C.\n",
    "\n",
    "Also note that just like a normal Python string, the __Seq__ object is in some ways ``read-only''.  If you need to edit your sequence, for example simulating a point mutation, look at the Section sec:mutable-seq below which talks about the __MutableSeq__ object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Slicing a sequence"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A more complicated example, let's get a slice of the sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('GATGGGCC', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq = Seq(\"GATCGATGGGCCTATATAGGATCGAAAATCGC\", IUPAC.unambiguous_dna)\n",
    "my_seq[4:12]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two things are interesting to note. First, this follows the normal conventions for Python strings.  So the first element of the sequence is 0 (which is normal for computer science, but not so normal for biology). When you do a slice the first item is included (i.e.~4 in this case) and the last is excluded (12 in this case), which is the way things work in Python, but of course not necessarily the way everyone in the world would expect. The main goal is to stay consistent with what Python does.\n",
    "\n",
    "The second thing to notice is that the slice is performed on the sequence data string, but the new object produced is another __Seq__ object which retains the alphabet information from the original __Seq__ object.\n",
    "\n",
    "Also like a Python string, you can do slices with a start, stop and _stride_ (the step size, which defaults to one).  For example, we can get the first, second and third codon positions of this DNA sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GCTGTAGTAAG\n",
      "AGGCATGCATC\n",
      "TAGCTAAGAC\n"
     ]
    }
   ],
   "source": [
    "print(my_seq[0::3])\n",
    "print(my_seq[1::3])\n",
    "print(my_seq[2::3])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another stride trick you might have seen with a Python string is the use of a -1 stride to reverse the string.  You can do this with a Seq object too:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('CGCTAAAAGCTAGGATATATCCGGGTAGCTAG', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq[::-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Turning Seq objects into strings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you really do just need a plain string, for example to write to a file, or insert into a database, then this is very easy to get:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'GATCGATGGGCCTATATAGGATCGAAAATCGC'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "str(my_seq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since calling str() on a Seq object returns the full sequence as a string,\n",
    "you often don't actually have to do this conversion explicitly.\n",
    "Python does this automatically in the print function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GATCGATGGGCCTATATAGGATCGAAAATCGC\n"
     ]
    }
   ],
   "source": [
    "print(my_seq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also use the Seq object directly with a %s placeholder when using the Python string formatting or interpolation operator (%):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      ">Name\n",
      "GATCGATGGGCCTATATAGGATCGAAAATCGC\n",
      "\n"
     ]
    }
   ],
   "source": [
    "fasta_format_string = \">Name\\n%s\\n\" % my_seq\n",
    "print(fasta_format_string)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This line of code constructs a simple FASTA format record (without worrying about line wrapping).\n",
    "Later we will describe a neat way to get a FASTA formatted\n",
    "string from a SeqRecord object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/tiago_antao/miniconda/lib/python3.5/site-packages/Bio/Seq.py:343: BiopythonDeprecationWarning: This method is obsolete; please use str(my_seq) instead of my_seq.tostring().\n",
      "  BiopythonDeprecationWarning)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'GATCGATGGGCCTATATAGGATCGAAAATCGC'"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq.tostring()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Concatenating or adding sequences"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Naturally, you can in principle add any two Seq objects together - just like you can with Python strings to concatenate them.  However, you can't add sequences with incompatible alphabets, such as a protein sequence and a DNA sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Incompatible alphabets IUPACProtein() and IUPACUnambiguousDNA()\n"
     ]
    }
   ],
   "source": [
    "protein_seq = Seq(\"EVRNAK\", IUPAC.protein)\n",
    "dna_seq = Seq(\"ACGT\", IUPAC.unambiguous_dna)\n",
    "try:\n",
    "    protein_seq + dna_seq\n",
    "except TypeError as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you _really_ wanted to do this, you'd have to first give both sequences generic alphabets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('EVRNAKACGT', Alphabet())"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from Bio.Alphabet import generic_alphabet\n",
    "protein_seq.alphabet = generic_alphabet\n",
    "dna_seq.alphabet = generic_alphabet\n",
    "protein_seq + dna_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is an example of adding a generic nucleotide sequence to an unambiguous IUPAC DNA sequence, resulting in an ambiguous nucleotide sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('GATCGATGC', NucleotideAlphabet())"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from Bio.Alphabet import generic_nucleotide\n",
    "nuc_seq = Seq(\"GATCGATGC\", generic_nucleotide)\n",
    "dna_seq = Seq(\"ACGT\", IUPAC.unambiguous_dna)\n",
    "nuc_seq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('ACGT', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dna_seq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('GATCGATGCACGT', NucleotideAlphabet())"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nuc_seq + dna_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may often have many sequences to add together, which can be done with a for loop like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('ACGTAACCGGTT', DNAAlphabet())"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from Bio.Alphabet import generic_dna\n",
    "list_of_seqs = [Seq(\"ACGT\", generic_dna), Seq(\"AACC\", generic_dna), Seq(\"GGTT\", generic_dna)]\n",
    "concatenated = Seq(\"\", generic_dna)\n",
    "for s in list_of_seqs:\n",
    "     concatenated += s\n",
    "concatenated"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or, a more elegant approach is to the use built in __sum__ function with its optional start value argument (which otherwise defaults to zero):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('ACGTAACCGGTT', DNAAlphabet())"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list_of_seqs = [Seq(\"ACGT\", generic_dna), Seq(\"AACC\", generic_dna), Seq(\"GGTT\", generic_dna)]\n",
    "sum(list_of_seqs, Seq(\"\", generic_dna))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Unlike the Python string, the Biopython Seq does not (currently) have a .join method."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Changing case"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python strings have very useful upper and lower methods for changing the case.\n",
    "As of Biopython 1.53, the Seq object gained similar methods which are alphabet aware.\n",
    "For example,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "acgtACGT\n",
      "ACGTACGT\n",
      "acgtacgt\n"
     ]
    }
   ],
   "source": [
    "dna_seq = Seq(\"acgtACGT\", generic_dna)\n",
    "print(dna_seq)\n",
    "print(dna_seq.upper())\n",
    "print(dna_seq.lower())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These are useful for doing case insensitive matching:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print(\"GTAC\" in dna_seq)\n",
    "print(\"GTAC\" in dna_seq.upper())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Note that strictly speaking the IUPAC alphabets are for upper case\n",
    "sequences only, thus:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('ACGT', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dna_seq = Seq(\"ACGT\", IUPAC.unambiguous_dna)\n",
    "dna_seq"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('acgt', DNAAlphabet())"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dna_seq.lower()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Nucleotide sequences and (reverse) complements"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For nucleotide sequences, you can easily obtain the complement or reverse\n",
    "complement of a Seq object using its built-in methods:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GATCGATGGGCCTATATAGGATCGAAAATCGC\n",
      "CTAGCTACCCGGATATATCCTAGCTTTTAGCG\n",
      "GCGATTTTCGATCCTATATAGGCCCATCGATC\n"
     ]
    }
   ],
   "source": [
    "my_seq = Seq(\"GATCGATGGGCCTATATAGGATCGAAAATCGC\", IUPAC.unambiguous_dna)\n",
    "print(my_seq)\n",
    "print(my_seq.complement())\n",
    "print(my_seq.reverse_complement())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As mentioned earlier, an easy way to just reverse a Seq object (or a\n",
    "Python string) is slice it with -1 step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('CGCTAAAAGCTAGGATATATCCGGGTAGCTAG', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_seq[::-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In all of these operations, the alphabet property is maintained. This is very\n",
    "useful in case you accidentally end up trying to do something weird like take\n",
    "the (reverse)complement of a protein sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Proteins do not have complements!\n"
     ]
    }
   ],
   "source": [
    "protein_seq = Seq(\"EVRNAK\", IUPAC.protein)\n",
    "try:\n",
    "    protein_seq.complement()\n",
    "except ValueError as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Transcription"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before talking about transcription, I want to try and clarify the strand issue.\n",
    "Consider the following (made up) stretch of double stranded DNA which\n",
    "encodes a short peptide:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "|    | DNA coding strand (Crick strand, strand +1)    |    |\n",
    "| -- | ---------------------------------------------- | -- |\n",
    "| 5' | ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG        | 3' |\n",
    "| 3' | TACCGGTAACATTACCCGGCGACTTTCCCACGGGCTATC        | 5' |\n",
    "|    | DNA template strand (Watson strand, strand -1) |    |\n",
    "|    |           __Transcription__                    |    |\n",
    "| 5' | AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG}       | 3' |\n",
    "|    | Single stranded messenger RNA                  |    |\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The actual biological transcription process works from the template strand, doing a reverse complement (TCAG -> CUGA) to give the mRNA.  However, in Biopython and bioinformatics in general, we typically work directly with the coding strand because this means we can get the mRNA sequence just by switching T -> U.\n",
    "\n",
    "Now let's actually get down to doing a transcription in Biopython.  First, let's create Seq objects for the coding and template DNA strands:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG\n",
      "CTATCGGGCACCCTTTCAGCGGCCCATTACAATGGCCAT\n"
     ]
    }
   ],
   "source": [
    "coding_dna = Seq(\"ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG\", IUPAC.unambiguous_dna)\n",
    "print(coding_dna)\n",
    "template_dna = coding_dna.reverse_complement()\n",
    "print(template_dna)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These should match the figure above - remember by convention nucleotide sequences are normally read from the 5' to 3' direction, while in the figure the template strand is shown reversed.\n",
    "\n",
    "Now let's transcribe the coding strand into the corresponding mRNA, using the Seq object's built in transcribe method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "messenger_rna = coding_dna.transcribe()\n",
    "messenger_rna"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, all this does is switch T $\\rightarrow$ U, and adjust the alphabet.\n",
    "\n",
    "If you do want to do a true biological transcription starting with the template strand, then this becomes a two-step process:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('AUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAG', IUPACUnambiguousRNA())"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "template_dna.reverse_complement().transcribe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Seq object also includes a back-transcription method for going from the mRNA to the coding strand of the DNA.  Again, this is a simple U $\\rightarrow$ T substitution and associated change of alphabet:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "messenger_rna.back_transcribe()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Translation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sticking with the same example discussed in the transcription section above,\n",
    "now let's translate this mRNA into the corresponding protein sequence - again taking\n",
    "advantage of one of the Seq object's biological methods:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "messenger_rna.translate()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also translate directly from the coding strand DNA sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should notice in the above protein sequences that in addition to the end stop character, there is an internal stop as well.  This was a deliberate choice of example, as it gives an excuse to talk about some optional arguments, including different translation tables (Genetic Codes).\n",
    "\n",
    "The translation tables available in Biopython are based on those http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.c {from the NCBI} (see the next section of this tutorial).  By default, translation will use the *standard* genetic code (NCBI table id 1).\n",
    "Suppose we are dealing with a mitochondrial sequence.  We need to tell the translation function to use the relevant genetic code instead:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate(table=\"Vertebrate Mitochondrial\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also specify the table using the NCBI table number which is shorter, and often included in the feature annotation of GenBank files:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate(table=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, you may want to translate the nucleotides up to the first in frame stop codon,\n",
    "and then stop (as happens in nature):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGR*KGAR*', HasStopCodon(IUPACProtein(), '*'))"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGR', IUPACProtein())"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate(to_stop=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGRWKGAR*', HasStopCodon(IUPACProtein(), '*'))"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate(table=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGRWKGAR', IUPACProtein())"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate(table=2, to_stop=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that when you use the to_stop argument, the stop codon itself\n",
    "is not translated - and the stop symbol is not included at the end of your protein\n",
    "sequence.\n",
    "\n",
    "You can even specify the stop symbol if you don't like the default asterisk:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MAIVMGRWKGAR@', HasStopCodon(IUPACProtein(), '@'))"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "coding_dna.translate(table=2, stop_symbol=\"@\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, suppose you have a complete coding sequence CDS, which is to say a\n",
    "nucleotide sequence (e.g. mRNA -- after any splicing) which is a whole number\n",
    "of codons (i.e. the length is a multiple of three), commences with a start\n",
    "codon, ends with a stop codon, and has no internal in-frame stop codons.\n",
    "In general, given a complete CDS, the default translate method will do what\n",
    "you want (perhaps with the to_stop option). However, what if your\n",
    "sequence uses a non-standard start codon? This happens a lot in bacteria --\n",
    "for example the gene yaaX in *E. coli* K12:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('VKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HR*', HasStopCodon(ExtendedIUPACProtein(), '*'))"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gene = Seq(\"GTGAAAAAGATGCAATCTATCGTACTCGCACTTTCCCTGGTTCTGGTCGCTCCCATGGCA\" +\n",
    "           \"GCACAGGCTGCGGAAATTACGTTAGTCCCGTCAGTAAAATTACAGATAGGCGATCGTGAT\" + \n",
    "           \"AATCGTGGCTATTACTGGGATGGAGGTCACTGGCGCGACCACGGCTGGTGGAAACAACAT\" + \n",
    "           \"TATGAATGGCGAGGCAATCGCTGGCACCTACACGGACCGCCGCCACCGCCGCGCCACCAT\" + \n",
    "           \"AAGAAAGCTCCTCATGATCATCACGGCGGTCATGGTCCAGGCAAACATCACCGCTAA\",\n",
    "           generic_dna)\n",
    "gene.translate(table=\"Bacterial\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('VKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HHR', ExtendedIUPACProtein())"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gene.translate(table=\"Bacterial\", to_stop=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the bacterial genetic code GTG is a valid start codon,\n",
    "and while it does *normally* encode Valine, if used as a start codon it\n",
    "should be translated as methionine. This happens if you tell Biopython your\n",
    "sequence is a complete CDS:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('MKKMQSIVLALSLVLVAPMAAQAAEITLVPSVKLQIGDRDNRGYYWDGGHWRDH...HHR', ExtendedIUPACProtein())"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gene.translate(table=\"Bacterial\", cds=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition to telling Biopython to translate an alternative start codon as\n",
    "methionine, using this option also makes sure your sequence really is a valid\n",
    "CDS (you'll get an exception if not)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Translation Tables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the previous sections we talked about the Seq object translation method (and mentioned the equivalent function in the Bio.Seq module).\n",
    "Internally these use codon table objects derived from the NCBI information at\n",
    "ftp://ftp.ncbi.nlm.nih.gov/entrez/misc/data/gc.prt, also shown on\n",
    "http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi in a much more readable layout.\n",
    "\n",
    "As before, let's just focus on two choices: the Standard translation table, and the\n",
    "translation table for Vertebrate Mitochondrial DNA."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "standard_table = CodonTable.unambiguous_dna_by_name[\"Standard\"]\n",
    "mito_table = CodonTable.unambiguous_dna_by_name[\"Vertebrate Mitochondrial\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternatively, these tables are labeled with ID numbers 1 and 2, respectively:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "standard_table = CodonTable.unambiguous_dna_by_id[1]\n",
    "mito_table = CodonTable.unambiguous_dna_by_id[2]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can compare the actual tables visually by printing them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Table 1 Standard, SGC0\n",
      "\n",
      "  |  T      |  C      |  A      |  G      |\n",
      "--+---------+---------+---------+---------+--\n",
      "T | TTT F   | TCT S   | TAT Y   | TGT C   | T\n",
      "T | TTC F   | TCC S   | TAC Y   | TGC C   | C\n",
      "T | TTA L   | TCA S   | TAA Stop| TGA Stop| A\n",
      "T | TTG L(s)| TCG S   | TAG Stop| TGG W   | G\n",
      "--+---------+---------+---------+---------+--\n",
      "C | CTT L   | CCT P   | CAT H   | CGT R   | T\n",
      "C | CTC L   | CCC P   | CAC H   | CGC R   | C\n",
      "C | CTA L   | CCA P   | CAA Q   | CGA R   | A\n",
      "C | CTG L(s)| CCG P   | CAG Q   | CGG R   | G\n",
      "--+---------+---------+---------+---------+--\n",
      "A | ATT I   | ACT T   | AAT N   | AGT S   | T\n",
      "A | ATC I   | ACC T   | AAC N   | AGC S   | C\n",
      "A | ATA I   | ACA T   | AAA K   | AGA R   | A\n",
      "A | ATG M(s)| ACG T   | AAG K   | AGG R   | G\n",
      "--+---------+---------+---------+---------+--\n",
      "G | GTT V   | GCT A   | GAT D   | GGT G   | T\n",
      "G | GTC V   | GCC A   | GAC D   | GGC G   | C\n",
      "G | GTA V   | GCA A   | GAA E   | GGA G   | A\n",
      "G | GTG V   | GCG A   | GAG E   | GGG G   | G\n",
      "--+---------+---------+---------+---------+--\n"
     ]
    }
   ],
   "source": [
    "print(standard_table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Table 2 Vertebrate Mitochondrial, SGC1\n",
      "\n",
      "  |  T      |  C      |  A      |  G      |\n",
      "--+---------+---------+---------+---------+--\n",
      "T | TTT F   | TCT S   | TAT Y   | TGT C   | T\n",
      "T | TTC F   | TCC S   | TAC Y   | TGC C   | C\n",
      "T | TTA L   | TCA S   | TAA Stop| TGA W   | A\n",
      "T | TTG L   | TCG S   | TAG Stop| TGG W   | G\n",
      "--+---------+---------+---------+---------+--\n",
      "C | CTT L   | CCT P   | CAT H   | CGT R   | T\n",
      "C | CTC L   | CCC P   | CAC H   | CGC R   | C\n",
      "C | CTA L   | CCA P   | CAA Q   | CGA R   | A\n",
      "C | CTG L   | CCG P   | CAG Q   | CGG R   | G\n",
      "--+---------+---------+---------+---------+--\n",
      "A | ATT I(s)| ACT T   | AAT N   | AGT S   | T\n",
      "A | ATC I(s)| ACC T   | AAC N   | AGC S   | C\n",
      "A | ATA M(s)| ACA T   | AAA K   | AGA Stop| A\n",
      "A | ATG M(s)| ACG T   | AAG K   | AGG Stop| G\n",
      "--+---------+---------+---------+---------+--\n",
      "G | GTT V   | GCT A   | GAT D   | GGT G   | T\n",
      "G | GTC V   | GCC A   | GAC D   | GGC G   | C\n",
      "G | GTA V   | GCA A   | GAA E   | GGA G   | A\n",
      "G | GTG V(s)| GCG A   | GAG E   | GGG G   | G\n",
      "--+---------+---------+---------+---------+--\n"
     ]
    }
   ],
   "source": [
    "print(mito_table)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may find these following properties useful -- for example if you are trying\n",
    "to do your own gene finding:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['TAA', 'TAG', 'AGA', 'AGG']\n",
      "['ATT', 'ATC', 'ATA', 'ATG', 'GTG']\n",
      "T\n"
     ]
    }
   ],
   "source": [
    "print(mito_table.stop_codons)\n",
    "print(mito_table.start_codons)\n",
    "print(mito_table.forward_table[\"ACG\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparing Seq objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sequence comparison is actually a very complicated topic, and there is no easy\n",
    "way to decide if two sequences are equal. The basic problem is the meaning of\n",
    "the letters in a sequence are context dependent - the letter ``A'' could be part\n",
    "of a DNA, RNA or protein sequence. Biopython uses alphabet objects as part of\n",
    "each Seq object to try and capture this information - so comparing two\n",
    "Seq objects means considering both the sequence strings *and* the\n",
    "alphabets.\n",
    "\n",
    "For example, you might argue that the two DNA Seq objects\n",
    "Seq(\"ACGT\", IUPAC.unambiguous_dna) and\n",
    "Seq(\"ACGT\", IUPAC.ambiguous\\_dna) should be equal, even though\n",
    "they do have different alphabets. Depending on the context this could be\n",
    "important.\n",
    "\n",
    "This gets worse -- suppose you think Seq(\"ACGT\",\n",
    "IUPAC.unambiguous\\_dna) and Seq(\"ACGT\") (i.e. the default generic\n",
    "alphabet) should be equal. Then, logically, Seq(\"ACGT\", IUPAC.protein)\n",
    "and Seq(\"ACGT\") should also be equal. Now, in logic if $A=B$ and\n",
    "$B=C$, by transitivity we expect $A=C$. So for logical consistency we'd\n",
    "require Seq(\"ACGT\", IUPAC.unambiguous_dna) and Seq(\"ACGT\",\n",
    "IUPAC.protein) to be equal -- which most people would agree is just not right.\n",
    "This transitivity problem would also have implications for using Seq\n",
    "objects as Python dictionary keys."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "seq1 = Seq(\"ACGT\", IUPAC.unambiguous_dna)\n",
    "seq2 = Seq(\"ACGT\", IUPAC.unambiguous_dna)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, what does Biopython do? Well, the equality test is the default for Python\n",
    "objects -- it tests to see if they are the same object in memory. This is a\n",
    "very strict test:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print(seq1 == seq2)\n",
    "print(seq1 == seq1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you actually want to do this, you can be more explicit by using the Python id function,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print(id(seq1) == id(seq2))\n",
    "print(id(seq1) == id(seq1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, in every day use, your sequences will probably all have the same\n",
    "alphabet, or at least all be the same type of sequence (all DNA, all RNA, or\n",
    "all protein). What you probably want is to just compare the sequences as\n",
    "strings -- so do this explicitly:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print(str(seq1) == str(seq2))\n",
    "print(str(seq1) == str(seq1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As an extension to this, while you can use a Python dictionary with\n",
    "__Seq__ objects as keys, it is generally more useful to use the sequence a\n",
    "string for the key."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## MutableSeq Objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Just like the normal Python string, the __Seq__ object is ``read only'', or in Python terminology, immutable.  Apart from wanting the __Seq__ object to act like a string, this is also a useful default since in many biological applications you want to ensure you are not changing your sequence data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "my_seq = Seq(\"GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA\", IUPAC.unambiguous_dna)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Observe what happens if you try to edit the sequence:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'Seq' object does not support item assignment\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    my_seq[5] = \"G\"\n",
    "except Exception as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, you can convert it into a mutable sequence (a __MutableSeq__ object) and do pretty much anything you want with it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "MutableSeq('GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mutable_seq = my_seq.tomutable()\n",
    "mutable_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternatively, you can create a __MutableSeq__ object directly from a string:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from Bio.Seq import MutableSeq\n",
    "mutable_seq = MutableSeq(\"GCCATTGTAATGGGCCGCTGAAAGGGTGCCCGA\", IUPAC.unambiguous_dna)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Either way will give you a sequence object which can be changed:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "GCCATCGTAATGGGCCGCTGAAAGGGTGCCCGA\n",
      "GCCACGTAATGGGCCGCTGAAAGGGTGCCCGA\n",
      "AGCCCGTGGGAAAGTCGCCGGGTAATGCACCG\n"
     ]
    }
   ],
   "source": [
    "mutable_seq[5] = \"C\"\n",
    "print(mutable_seq)\n",
    "mutable_seq.remove(\"T\")\n",
    "print(mutable_seq)\n",
    "mutable_seq.reverse()\n",
    "print(mutable_seq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Do note that unlike the Seq object, the MutableSeq object's methods like reverse_complement() and reverse() act in-situ!\n",
    "\n",
    "An important technical difference between mutable and immutable objects in Python means that you can't use a MutableSeq object as a dictionary key, but you can use a Python string or \n",
    "a Seq object in this way.\n",
    "\n",
    "Once you have finished editing your a MutableSeq object, it's easy to get back to a read-only Seq object should you need to:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Seq('AGCCCGTGGGAAAGTCGCCGGGTAATGCACCG', IUPACUnambiguousDNA())"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "new_seq = mutable_seq.toseq()\n",
    "new_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also get a string from a MutableSeq object just like from a Seq object."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## UnknownSeq Objects"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The UnknownSeq object is a subclass of the basic Seq object\n",
    "and its purpose is to represent a\n",
    "sequence where we know the length, but not the actual letters making it up.\n",
    "You could of course use a normal Seq object in this situation, but it wastes\n",
    "rather a lot of memory to hold a string of a million ``N'' characters when you could\n",
    "just store a single letter ``N'' and the desired length as an integer.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UnknownSeq(20, alphabet = Alphabet(), character = '?')"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from Bio.Seq import UnknownSeq\n",
    "unk = UnknownSeq(20)\n",
    "unk"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "????????????????????\n",
      "20\n"
     ]
    }
   ],
   "source": [
    "print(unk)\n",
    "print(len(unk))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can of course specify an alphabet, meaning for nucleotide sequences\n",
    "the letter defaults to 'N' and for proteins 'X', rather than just '?'."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unk_dna = UnknownSeq(20, alphabet=IUPAC.ambiguous_dna)\n",
    "unk_dna"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NNNNNNNNNNNNNNNNNNNN\n"
     ]
    }
   ],
   "source": [
    "print(unk_dna)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use all the usual __Seq__ object methods too, note these give back\n",
    "memory saving __UnknownSeq__ objects where appropriate as you might expect:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unk_dna"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unk_dna.complement()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UnknownSeq(20, alphabet = IUPACAmbiguousDNA(), character = 'N')"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unk_dna.reverse_complement()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UnknownSeq(20, alphabet = IUPACAmbiguousRNA(), character = 'N')"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unk_dna.transcribe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "UnknownSeq(6, alphabet = ProteinAlphabet(), character = 'X')"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unk_protein = unk_dna.translate()\n",
    "unk_protein"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "XXXXXX\n",
      "6\n"
     ]
    }
   ],
   "source": [
    "print(unk_protein)\n",
    "print(len(unk_protein))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may be able to find a use for the UnknownSeq object in your own\n",
    "code, but it is more likely that you will first come across them in a\n",
    "SeqRecord object created by Bio.SeqIO.\n",
    "Some sequence file formats don't always include the actual sequence, for\n",
    "example GenBank and EMBL files may include a list of features but for the\n",
    "sequence just present the contig information.  Alternatively, the QUAL files\n",
    "used in sequencing work hold quality scores but they *never* contain a\n",
    "sequence -- instead there is a partner FASTA file which *does* have the\n",
    "sequence."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Working with strings directly"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To close this chapter, for those you who *really* don't want to use the sequence\n",
    "objects (or who prefer a functional programming style to an object orientated one),\n",
    "there are module level functions in Bio.Seq will accept plain Python strings,\n",
    "Seq objects (including UnknownSeq objects) or MutableSeq objects:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CTAACCAGCAGCACGACCACCCTTCCAACGACCCATAACAGC\n",
      "GCUGUUAUGGGUCGUUGGAAGGGUGGUCGUGCUGCUGGUUAG\n",
      "GCTGTTATGGGTCGTTGGAAGGGTGGTCGTGCTGCTGGTTAG\n",
      "AVMGRWKGGRAAG*\n"
     ]
    }
   ],
   "source": [
    "from Bio.Seq import reverse_complement, transcribe, back_transcribe, translate\n",
    "my_string = \"GCTGTTATGGGTCGTTGGAAGGGTGGTCGTGCTGCTGGTTAG\"\n",
    "print(reverse_complement(my_string))\n",
    "print(transcribe(my_string))\n",
    "print(back_transcribe(my_string))\n",
    "print(translate(my_string))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You are, however, encouraged to work with Seq objects by default."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
